import type { AxFiles } from '@/api/modules/ax/files/types';
import { filesResetForm, filesShowForm, filesForm } from './form';
import { filesTable } from './table';
import {
  deleteFiles,
  fetchFilesById,
  fetchFilesList,
  exportFiles,
} from '@/api/modules/ax/files/files';
import { response } from '@/utils/table/table';
import { setContextMenu } from '@/views/components/contextmenu/data';

export const filesList = async () => {
  try {
    filesTable.value.loading = true;
    const { data } = await fetchFilesList(filesTable.value.query);
    filesTable.value.data = data.rows;
    filesTable.value.query.total = data.total;
    filesTable.value.loading = false;
  } catch (error) {
    filesTable.value.loading = false;
  }
};

export const filesEdit = async (id?: number) => {
  let targetId: number | string = id ? id : filesTable.value.keys[0];
  filesTable.value.loading = true;
  const { data } = await fetchFilesById(targetId);
  if (data.data) {
    filesForm.value = data.data;
    filesShowForm.value = true;
  }
  filesTable.value.loading = false;
};

export const filesCreate = async () => {
  filesResetForm();
  filesShowForm.value = true;
};

export const filesDelete = async (id?: number) => {
  let ids = id ? [id] : filesTable.value.keys;
  await response(deleteFiles, ids);
  await filesList();
  filesTable.value.keys = [];
};

// 导出EXCEL文件
export const filesExport = () => {
  return exportFiles(filesTable.value.query);
};

/**
 * @description:搜索
 * 需要将页码设为第一页，避免翻页后搜不到内容
 */
export const filesSearch = () => {
  filesTable.value.query.pageNum = 1;
  filesList();
};
/**
 * @description:
 *  显示右键菜单
 *  在表格和卡片中复用
 * @param {AxTest} item
 */
export const displayFilesMenu = (item: AxFiles) => {
  filesForm.value = item;
  filesTable.value.keys = [item.fileId];
  setContextMenu({
    items: filesTable.value.contextmenu,
  });
};
